package com.xz.stu.server.controller;

import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.json.JsonUtils;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.framework.excel.core.util.ExcelUtils;
import cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils;
import com.xz.stu.server.vo.teacher.*;
import com.xz.stu.server.service.TeacherService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;

import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;

@Tag(name = "管理后台 - 教师管理")
@RestController
@RequestMapping("admin-api/school/teacher")
@Validated
public class TeacherController {

    @Resource
    private TeacherService teacherService;
    @Autowired
    private StringRedisTemplate redisTemplate;

    @PostMapping("/create")
    @Operation(summary = "创建教师")
    public CommonResult<Long> createTeacher(@Valid @RequestBody TeacherCreateReqVO createReqVO) {
        return success(teacherService.createTeacher(createReqVO));
    }

    @PutMapping("/update")
    @Operation(summary = "更新教师")
    public CommonResult<Boolean> updateTeacher(@Valid @RequestBody TeacherUpdateReqVO updateReqVO) {
        teacherService.updateTeacher(updateReqVO);
        return success(true);
    }

    @DeleteMapping("/delete/{id}")
    @Operation(summary = "删除教师")
    public CommonResult<Boolean> deleteTeacher(@PathVariable("id") List<Long> id) {
        teacherService.deleteTeacher(id);
        return success(true);
    }

    @GetMapping("/get/{id}")
    @Operation(summary = "获得教师")
    public CommonResult<TeacherRespVO> getTeacher(@PathVariable("id") Long id) {
        return success(teacherService.getTeacher(id));
    }

    @GetMapping("/list")
    @Operation(summary = "获得教师列表")
    public CommonResult<List<TeacherRespVO>> getTeacherList(@Valid TeacherListReqVO listReqVO) {
        return success(teacherService.getTeacherList(listReqVO));
    }

    @GetMapping("/page")
    @Operation(summary = "获得教师列表-分页")
    public CommonResult<PageResult<TeacherRespVO>> getTeacherListPage(@Valid TeacherListPageReqVO listReqVO) {
        return success(teacherService.getTeacherListPage(listReqVO));
    }

    // 导出教师信息为 Excel 文件
    @GetMapping("/export")
    public void exportTeachers(HttpServletResponse response, @Valid TeacherListPageReqVO listReqVO) throws IOException {
        PageResult<TeacherRespVO> teacherListPage = teacherService.getTeacherListPage(listReqVO);
        List<TeacherExcelVO> teacherList = BeanUtils.toBean(teacherListPage.getList(), TeacherExcelVO.class);
        AtomicInteger i = new AtomicInteger();
        teacherList.forEach(teacher -> {
            teacher.setNo((long) i.incrementAndGet());
            teacher.setGenderC(teacher.getGender() == 0 ? "男" : "女");
        });
        ExcelUtils.write(response, "教师信息.xlsx", "教师信息", TeacherExcelVO.class, teacherList);
    }

    // 导入模版
    @GetMapping("/downloadTemplate")
    public void downloadTemplate(HttpServletResponse response) throws IOException {
        TeacherTemplateVO teacherTemplateVO = new TeacherTemplateVO();
        teacherTemplateVO.setTeacherId("2021001(示例数据请删除)");
        teacherTemplateVO.setName("李四(示例数据请删除)");
        teacherTemplateVO.setGenderC("男(示例数据请删除)");
        teacherTemplateVO.setTitle("讲师(示例数据请删除)");
        teacherTemplateVO.setPhone("13900000000(示例数据请删除)");
        teacherTemplateVO.setDeptName("计算机科学与技术(示例数据请删除)");
        teacherTemplateVO.setBirthDate("1990-01-01(示例数据请删除)");
        teacherTemplateVO.setEntryDate("2020-09-01(示例数据请删除)");
        ExcelUtils.write(response, "教师信息.xlsx(示例数据请删除)", "教师信息", TeacherTemplateVO.class, Collections.singletonList(teacherTemplateVO));
    }

    // 导入教师信息从 Excel 文件
    @PostMapping("/import")
    public CommonResult<Map<String, String>> importTeachers(@RequestParam("file") MultipartFile file) throws IOException {
        if (file.isEmpty()) {
            HashMap<String, String> map = new HashMap<>();
            map.put("code", "300");
            map.put("msg", "文件为空，请选择有效的 Excel 文件。");
            return success(map);
        }
        List<TeacherTemplateVO> teachers = ExcelUtils.read(file, TeacherTemplateVO.class);
        return teacherService.importTeachers(teachers);
    }

    // 导出异常信息
    @GetMapping("/exportAbnormal")
    public void exportAbnormal(HttpServletResponse response) throws IOException {
        Long id = Objects.requireNonNull(SecurityFrameworkUtils.getLoginUser()).getId();
        // 构架 key
        String key = "teacher:import:abnormal:" + id;
        String s = redisTemplate.opsForValue().get(key);
        // 删除 redis 缓存信息
        Boolean delete = redisTemplate.delete(key);
        List<TeacherTemplateAbnormalVO> teacherList = JsonUtils.parseArray(s, TeacherTemplateAbnormalVO.class);

        ExcelUtils.write(response, "教师信息.xlsx", "教师信息", TeacherTemplateAbnormalVO.class, teacherList);
    }
}
